package com.wangyi.system.service.impl;

import com.wangyi.system.domain.Role;
import com.wangyi.system.mapper.RoleMapper;
import com.wangyi.system.service.IRoleService;
import com.wangyi.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 添加
     * @param role
     */
    @Override
    @Transactional
    public void add(Role role) {
        super.add(role);
        addData(role);
    }

    /**
     * 公共方法添加
     * @param role
     */
    private void addData(Role role) {
        List<Long> menus = role.getMenus();
        // 添加中间表
        if (menus.size() > 0) {
            roleMapper.addRoleMenu(role.getId(), menus);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0) {
            roleMapper.addRolePermissions(role.getId(), permissions);
        }
    }

    /**
     * 修改
     * @param role
     */
    @Override
    @Transactional
    public void update(Role role) {
        // 先删除旧权限
        roleMapper.delRoleMenuByRoleId(role.getId());
        roleMapper.delRolePermissionByRoleId(role.getId());
        // 再添加新的权限
        addData(role);
        super.update(role);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    @Transactional
    public void del(Long id) { // id是角色id
        // 删除相关中间表
        roleMapper.delRoleMenuByRoleId(id);
        roleMapper.delRolePermissionByRoleId(id);
        roleMapper.delEmployeeRoleByRoleId(id);
        // 最后删，因为有外键约束，先删报错
        super.del(id);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    public void patchDelete(Long[] ids) {
        for (Long id : ids) {
            del(id);
        }
        super.patchDelete(ids);
    }
}

